package main.com.demo.dao.impl;

import main.com.demo.dao.UserDAO;
import main.com.demo.entity.User;
import main.com.demo.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDAOImpl implements UserDAO {
    @Override
    public int register(User user) {
        // 1. 创建QueryRunner对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

        // 2. 入库的SQL
        String sql = "insert into user values(null, ?,?,?, ?,?,?, ?,?,?)";

        // 3. 执行SQL
        try {
            // result：受影响的行数
            return qr.update(sql, user.getName(), user.getPassword(),
                    user.getAge(), user.getSex(), user.getEmail(),
                    user.getBirthday(), user.getHobby(),
                    user.getAddress(), user.getDescription());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean checkName(String name) {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select count(*) from user where name=?";
        Long count;
        try {
            count = qr.query(sql, new ScalarHandler<Long>(), name);
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            // 处理DAO层自己的异常
            // ...

            // 将异常抛给调用者（Service）,让调用者处理自己的异常
            throw new RuntimeException("查询用户名是否存在异常！" + e);
        }
    }

    @Override
    public User login(String username, String password) {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from user where name=? and password=?";
        try {
            return qr.query(sql, new BeanHandler<User>(User.class), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("登录失败！" + e);
        }
    }

}
